<?php

namespace app\shopapi\model;

use app\admin\model\shop\Category;
use app\api\model\mall\Area;
use app\api\model\Qrcode;
use think\Db;
use think\Loader;
use think\Log;
use think\Model;
use traits\model\SoftDelete;


class Shop extends Model
{

    use SoftDelete;



    // 表名
    protected $name = 'shop';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';

    // 追加属性
    protected $append = [
        //'start_time_text',
        //'end_time_text',
        //'id_card_time_text'
    ];


    public function getSubjectType()
    {
        return [1=>'个体工商户',2=>'个人',3=>'企业'];
    }



    public function getStartTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['start_time']) ? $data['start_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getEndTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['end_time']) ? $data['end_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getIdCardTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['id_card_time']) ? $data['id_card_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    protected function setIdCardTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    /**
     * 变更会员余额
     * @param int    $money   余额
     * @param int    $shop_id 商户ID
     * @param string $memo    备注
     */
    public static function money($money, $shop_id, $memo,$type=0)
    {
        Db::startTrans();
        try {
            $shop = self::lock(true)->find($shop_id);
            if ($shop && $money != 0) {
                $before = $shop->money;
                //$after = $user->money + $money;
                $after = function_exists('bcadd') ? bcadd($shop->money, $money, 4) : $shop->money + $money;
                if ($money>0){
                    $total_money =  bcadd($shop->money, $money, 4);
                } else {
                    $total_money = $shop->total_money;
                }
                //更新会员信息
                $shop->save(['money' => $after,'total_money'=>$total_money]);
                //写入日志
                MoneyLog::create(['shop_id' => $shop_id,'user_id' => $shop->user_id, 'money' => $money, 'before' => $before, 'after' => $after, 'memo' => $memo, 'type' => $type]);
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
        }
    }

    //
    //
    public function ceshiadd($params)
    {
        Db::startTrans();
        try {
            $model = Shop::get($params['shop_id']);
            $data = [
                'shop_name'=>array_key_exists('shop_name',$params)?$params['shop_name']:'',//店铺名称
                'category_id'=>array_key_exists('category_id',$params)?$params['category_id']:'',//经营类目id
                'address'=>array_key_exists('address',$params)?$params['address']:'',
                //'province_code'=>$params['province_code'],
                //'city_code'=>$params['city_code'],
                //'area_code'=>$params['area_code'],
                'lat'=>array_key_exists('lat',$params)?$params['lat']:'',
                'lng'=>array_key_exists('lng',$params)?$params['lng']:'',
                'commission_rate'=>array_key_exists('commission_rate',$params)?$params['commission_rate']:'',//佣金比例
                //'collection_code_number'=>$params['collection_code_number'],//收款码编号
                'start_time'=>array_key_exists('start_time',$params)?$params['start_time']:'',//开始营业时间
                'end_time'=>array_key_exists('end_time',$params)?$params['end_time']:'',//营业结束时间
                'work_week'=>array_key_exists('work_week',$params)?$params['work_week']:'',//工作日
                'banner_img'=>array_key_exists('banner_img',$params)?$params['banner_img']:'',//店铺门头照
                'interior_img'=>array_key_exists('interior_img',$params)?$params['interior_img']:'',//内景照
                //'group_photo_img'=>array_key_exists('group_photo_img',$params)?$params['group_photo_img']:'',//推手门店合影
                'realname'=>array_key_exists('realname',$params)?$params['realname']:'',//商家姓名
                'mobile'=>array_key_exists('mobile',$params)?$params['mobile']:'',//商家电话
                //'email'=>array_key_exists('email',$params)?$params['email']:'',//商家邮箱
                'subject_type'=>array_key_exists('subject_type',$params)?$params['subject_type']:'',//店铺主题类型
                'business_license_img'=>array_key_exists('business_license_img',$params)?$params['business_license_img']:'',//营业执照
                'business_license_num'=>array_key_exists('business_license_num',$params)?$params['business_license_num']:'',//营业执照号
                //'business_license_start_dt'=>$params['business_license_start_dt'],//营业执照开始日期
                //'business_license_end_dt'=>$params['business_license_end_dt'],//营业执照结束日期
                //'business_license_address'=>$params['business_license_address'],//营业执照地址
                'business_license_name'=>array_key_exists('business_license_name',$params)?$params['business_license_name']:'',//营业执照名称
                'body_name'=>array_key_exists('body_name',$params)?$params['body_name']:'',//主体名称
                'front_id_card_img'=>array_key_exists('front_id_card_img',$params)?$params['front_id_card_img']:'',//身份证正面图片
                'reverse_id_card_img'=>array_key_exists('reverse_id_card_img',$params)?$params['reverse_id_card_img']:'',//身份证反面图片
                'id_card_name'=>array_key_exists('id_card_name',$params)?$params['id_card_name']:'',//证件姓名
                'id_card_num'=>array_key_exists('id_card_num',$params)?$params['id_card_num']:'',//证件号码
                //'id_card_start_time'=>$params['id_card_start_time'],//证件有效开始日期
                //'id_card_end_time'=>$params['id_card_end_time'],//证件有效结束日期
                'legal_person_phone'=>array_key_exists('legal_person_phone',$params)?$params['legal_person_phone']:'',//法人手机号
                //'signature_img'=>array_key_exists('signature_img',$params)?$params['signature_img']:'',//法人签名
                'bank_type'=>array_key_exists('bank_type',$params)?$params['bank_type']:'',//账户类型
                //'bank_img'=>array_key_exists('bank_img',$params)?$params['bank_img']:'',//银行卡图片
                'bank_num'=>array_key_exists('bank_num',$params)?$params['bank_num']:'',//银行卡号
                'bank_account_person'=>array_key_exists('bank_account_person',$params)?$params['bank_account_person']:'',//开户人
                'bank'=>array_key_exists('bank',$params)?$params['bank']:'',//开户银行支行
                'bank_name'=>array_key_exists('bank_name',$params)?$params['bank_name']:'',//开户银行名称
                //'bank_code'=>$params['bank_code'],//联行号
                'bank_card_img'=>array_key_exists('bank_name',$params)?$params['bank_card_img']:'',//结算卡正面（对私必传）
                'bank_card_back_img'=>array_key_exists('bank_name',$params)?$params['bank_card_back_img']:'',//结算卡反面（对私必传）
                //'alipay_signing_account'=>$params['alipay_signing_account'],//支付宝签约账号
                //'wechat_signing_account'=>$params['wechat_signing_account'],//微信签约账号
                'audit_status'=>0,
                'is_draft'=>array_key_exists('is_draft',$params)?$params['is_draft']:'',
                'merchant_img_permit_for_bank_account'=>array_key_exists('merchant_img_permit_for_bank_account',$params)?$params['merchant_img_permit_for_bank_account']:'',//开户许可证（对公必传）
                'is_admin'=>1
                //'shop_no'=>\fast\Random::numeric(10),
                //'out_merchant_no'=>$params['shop_id'].'_'.\fast\Random::numeric(8)
            ];

            if (empty($model['out_member_no'])){
                $data['out_member_no'] = $model->user_id.'_'.\fast\Random::numeric(8);
            }
            if (empty($model['out_merchant_no'])){
                $data['out_merchant_no'] = $params['shop_id'].'_'.\fast\Random::numeric(8);
            }
            $validate = Loader::validate('Shop');
            if(!$validate->check($data)){
                throw new \Exception($validate->getError());
            }
            //dump($data);die;
            $res =  $model->save($data);

            //if ($res){
            $infeed_model = new \app\shopapi\model\lakala\ShopInfeed();

            $infeed_res = $infeed_model->memberapply($model->shop_id);
            Db::commit();

            return $infeed_res;

        } catch (\Exception $e) {
            Db::rollback();
            throw new \Exception($e->getMessage());
        }


    }

    //申请入驻
    public function add($params)
    {
        Db::startTrans();

        try {
            //$model = new Shop();
            $model = Shop::get($params['shop_id']);
            $data = [
                'shop_name'=>array_key_exists('shop_name',$params)?$params['shop_name']:'',//店铺名称
                'category_id'=>array_key_exists('category_id',$params)?$params['category_id']:'',//经营类目id
                'address'=>array_key_exists('address',$params)?$params['address']:'',
                //'province_code'=>$params['province_code'],
                //'city_code'=>$params['city_code'],
                //'area_code'=>$params['area_code'],
                'lat'=>array_key_exists('lat',$params)?$params['lat']:'',
                'lng'=>array_key_exists('lng',$params)?$params['lng']:'',
                'commission_rate'=>array_key_exists('commission_rate',$params)?$params['commission_rate']:'',//佣金比例
                //'collection_code_number'=>$params['collection_code_number'],//收款码编号
                'start_time'=>array_key_exists('start_time',$params)?$params['start_time']:'',//开始营业时间
                'end_time'=>array_key_exists('end_time',$params)?$params['end_time']:'',//营业结束时间
                'work_week'=>array_key_exists('work_week',$params)?$params['work_week']:'',//工作日
                'banner_img'=>array_key_exists('banner_img',$params)?$params['banner_img']:'',//店铺门头照
                'interior_img'=>array_key_exists('interior_img',$params)?$params['interior_img']:'',//内景照
                //'group_photo_img'=>array_key_exists('group_photo_img',$params)?$params['group_photo_img']:'',//推手门店合影
                'realname'=>array_key_exists('realname',$params)?$params['realname']:'',//商家姓名
                'mobile'=>array_key_exists('mobile',$params)?$params['mobile']:'',//商家电话
                //'email'=>array_key_exists('email',$params)?$params['email']:'',//商家邮箱
                'subject_type'=>array_key_exists('subject_type',$params)?$params['subject_type']:'',//店铺主题类型
                'business_license_img'=>array_key_exists('business_license_img',$params)?$params['business_license_img']:'',//营业执照
                'business_license_num'=>array_key_exists('business_license_num',$params)?$params['business_license_num']:'',//营业执照号
                //'business_license_start_dt'=>$params['business_license_start_dt'],//营业执照开始日期
                //'business_license_end_dt'=>$params['business_license_end_dt'],//营业执照结束日期
                //'business_license_address'=>$params['business_license_address'],//营业执照地址
                'business_license_name'=>array_key_exists('business_license_name',$params)?$params['business_license_name']:'',//营业执照名称
                'body_name'=>array_key_exists('body_name',$params)?$params['body_name']:'',//主体名称
                'front_id_card_img'=>array_key_exists('front_id_card_img',$params)?$params['front_id_card_img']:'',//身份证正面图片
                'reverse_id_card_img'=>array_key_exists('reverse_id_card_img',$params)?$params['reverse_id_card_img']:'',//身份证反面图片
                'id_card_name'=>array_key_exists('id_card_name',$params)?$params['id_card_name']:'',//证件姓名
                'id_card_num'=>array_key_exists('id_card_num',$params)?$params['id_card_num']:'',//证件号码
                //'id_card_start_time'=>$params['id_card_start_time'],//证件有效开始日期
                //'id_card_end_time'=>$params['id_card_end_time'],//证件有效结束日期
                'legal_person_phone'=>array_key_exists('legal_person_phone',$params)?$params['legal_person_phone']:'',//法人手机号
                'signature_img'=>array_key_exists('signature_img',$params)?$params['signature_img']:'',//法人签名
                'bank_type'=>array_key_exists('bank_type',$params)?$params['bank_type']:'',//账户类型
                //'bank_img'=>array_key_exists('bank_img',$params)?$params['bank_img']:'',//银行卡图片
                'bank_num'=>array_key_exists('bank_num',$params)?$params['bank_num']:'',//银行卡号
                'bank_account_person'=>array_key_exists('bank_account_person',$params)?$params['bank_account_person']:'',//开户人
                'bank'=>array_key_exists('bank',$params)?$params['bank']:'',//开户银行支行
                'bank_name'=>array_key_exists('bank_name',$params)?$params['bank_name']:'',//开户银行名称
                //'bank_code'=>$params['bank_code'],//联行号
                'bank_card_img'=>array_key_exists('bank_name',$params)?$params['bank_card_img']:'',//结算卡正面（对私必传）
                'bank_card_back_img'=>array_key_exists('bank_name',$params)?$params['bank_card_back_img']:'',//结算卡反面（对私必传）
                //'alipay_signing_account'=>$params['alipay_signing_account'],//支付宝签约账号
                //'wechat_signing_account'=>$params['wechat_signing_account'],//微信签约账号
                'audit_status'=>0,
                'is_draft'=>array_key_exists('is_draft',$params)?$params['is_draft']:'',
                'merchant_img_permit_for_bank_account'=>array_key_exists('merchant_img_permit_for_bank_account',$params)?$params['merchant_img_permit_for_bank_account']:'',//开户许可证（对公必传）
                //'shop_no'=>\fast\Random::numeric(10),
                //'out_merchant_no'=>$params['shop_id'].'_'.\fast\Random::numeric(8)
            ];

            if (empty($model['out_member_no'])){
                $data['out_member_no'] = $model->user_id.'_'.\fast\Random::numeric(8);
            }
            if (empty($model['out_merchant_no'])){
                $data['out_merchant_no'] = $params['shop_id'].'_'.\fast\Random::numeric(8);
            }
            $validate = Loader::validate('Shop');
            if(!$validate->check($data)){
                throw new \Exception($validate->getError());
            }
            //dump($data);die;
            $res =  $model->save($data);

            //if ($res){
                $infeed_model = new \app\shopapi\model\lakala\ShopInfeed();

                $infeed_res = $infeed_model->apply($model->shop_id);
                Db::commit();

                return $infeed_res;
            /*} else {
                Db::rollback();
                throw new \Exception('添加失败');
            }*/

        } catch (\Exception $e) {
            Db::rollback();
            throw new \Exception($e->getMessage());
        }
    }

    //保存草稿
    public function draft($params)
    {
        Db::startTrans();

        try {
            //$model = new Shop();
            $model = Shop::get($params['shop_id']);
            $data = [
                //'user_id'=>$params['user_id'],
                'shop_name'=>array_key_exists('shop_name',$params)?$params['shop_name']:'',//店铺名称
                'category_id'=>array_key_exists('category_id',$params)?$params['category_id']:'',//经营类目id
                'address'=>array_key_exists('address',$params)?$params['address']:'',
                //'province_code'=>$params['province_code'],
                //'city_code'=>$params['city_code'],
                //'area_code'=>$params['area_code'],
                'lat'=>array_key_exists('lat',$params)?$params['lat']:'',
                'lng'=>array_key_exists('lng',$params)?$params['lng']:'',
                'commission_rate'=>array_key_exists('commission_rate',$params)?$params['commission_rate']:'',//佣金比例
                //'collection_code_number'=>$params['collection_code_number'],//收款码编号
                'start_time'=>array_key_exists('start_time',$params)?$params['start_time']:'',//开始营业时间
                'end_time'=>array_key_exists('end_time',$params)?$params['end_time']:'',//营业结束时间
                'work_week'=>array_key_exists('work_week',$params)?$params['work_week']:'',//工作日
                'banner_img'=>array_key_exists('banner_img',$params)?$params['banner_img']:'',//店铺门头照
                'interior_img'=>array_key_exists('interior_img',$params)?$params['interior_img']:'',//内景照
                //'group_photo_img'=>array_key_exists('group_photo_img',$params)?$params['group_photo_img']:'',//推手门店合影
                'realname'=>array_key_exists('realname',$params)?$params['realname']:'',//商家姓名
                'mobile'=>array_key_exists('mobile',$params)?$params['mobile']:'',//商家电话
                //'email'=>array_key_exists('email',$params)?$params['email']:'',//商家邮箱
                'subject_type'=>array_key_exists('subject_type',$params)?$params['subject_type']:'',//店铺主题类型
                'business_license_img'=>array_key_exists('business_license_img',$params)?$params['business_license_img']:'',//营业执照
                'business_license_num'=>array_key_exists('business_license_num',$params)?$params['business_license_num']:'',//营业执照号
                //'business_license_start_dt'=>$params['business_license_start_dt'],//营业执照开始日期
                //'business_license_end_dt'=>$params['business_license_end_dt'],//营业执照结束日期
                //'business_license_address'=>$params['business_license_address'],//营业执照地址
                'business_license_name'=>array_key_exists('business_license_name',$params)?$params['business_license_name']:'',//营业执照名称
                'body_name'=>array_key_exists('body_name',$params)?$params['body_name']:'',//主体名称
                'front_id_card_img'=>array_key_exists('front_id_card_img',$params)?$params['front_id_card_img']:'',//身份证正面图片
                'reverse_id_card_img'=>array_key_exists('reverse_id_card_img',$params)?$params['reverse_id_card_img']:'',//身份证反面图片
                'id_card_name'=>array_key_exists('id_card_name',$params)?$params['id_card_name']:'',//证件姓名
                'id_card_num'=>array_key_exists('id_card_num',$params)?$params['id_card_num']:'',//证件号码
                //'id_card_start_time'=>$params['id_card_start_time'],//证件有效开始日期
                //'id_card_end_time'=>$params['id_card_end_time'],//证件有效结束日期
                'legal_person_phone'=>array_key_exists('legal_person_phone',$params)?$params['legal_person_phone']:'',//法人手机号
                'signature_img'=>array_key_exists('signature_img',$params)?$params['signature_img']:'',//法人签名
                'bank_type'=>array_key_exists('bank_type',$params)?$params['bank_type']:'',//账户类型
                //'bank_img'=>array_key_exists('bank_img',$params)?$params['bank_img']:'',//银行卡图片
                'bank_num'=>array_key_exists('bank_num',$params)?$params['bank_num']:'',//银行卡号
                'bank_account_person'=>array_key_exists('bank_account_person',$params)?$params['bank_account_person']:'',//开户人
                'bank'=>array_key_exists('bank',$params)?$params['bank']:'',//开户银行支行
                'bank_name'=>array_key_exists('bank_name',$params)?$params['bank_name']:'',//开户银行名称
                //'bank_code'=>$params['bank_code'],//联行号
                'bank_card_img'=>array_key_exists('bank_name',$params)?$params['bank_card_img']:'',//结算卡正面（对私必传）
                'bank_card_back_img'=>array_key_exists('bank_name',$params)?$params['bank_card_back_img']:'',//结算卡反面（对私必传）
                //'alipay_signing_account'=>$params['alipay_signing_account'],//支付宝签约账号
                //'wechat_signing_account'=>$params['wechat_signing_account'],//微信签约账号
                //'audit_status'=>1,
                'is_draft'=>array_key_exists('is_draft',$params)?$params['is_draft']:'',
                'merchant_img_permit_for_bank_account'=>array_key_exists('merchant_img_permit_for_bank_account',$params)?$params['merchant_img_permit_for_bank_account']:'',//开户许可证（对公必传）
                //'out_member_no'=>$params['shop_id'].'_'.\fast\Random::numeric(8),
                //'out_merchant_no'=>$params['shop_id'].'_'.\fast\Random::numeric(8)
            ];
            /*if (empty($model['out_member_no'])){
                $data['out_member_no'] = $params['shop_id'].'_'.\fast\Random::numeric(8);
            }
            if (empty($model['out_merchant_no'])){
                $data['out_merchant_no'] = $params['shop_id'].'_'.\fast\Random::numeric(8);
            }*/

            $res =  $model->save($data);

            if ($res){
                Db::commit();
                return $model;
            } else {
                Db::rollback();
                throw new \Exception('添加失败');
            }

        } catch (\Exception $e) {
            Db::rollback();
            throw new \Exception($e->getMessage());
        }
    }


    //根据区的adcode获取省市
    public function getProvinceCode($area_code)
    {
        $area = Area::get(['adcode'=>$area_code,'level'=>3]);

        $city = Area::get(['id'=>$area->pid,'level'=>2]);

        $province = Area::get(['id'=>$city->pid,'level'=>1]);

        $data = [
            'province_code'=>$province->adcode,
            'city_code'=>$city->adcode,
            'area_code'=>$area->adcode,
        ];

        return $data;
    }

    //申请列表
    public function lists($user_id)
    {
        $user = ShopUser::get($user_id);
        $lists = Shop::alias('s')
            ->join('shop_admin sa','s.shop_id = sa.shop_id')
            ->join('shop_user su','sa.mobile = su.mobile')
            //->where(['su.user_id'=>$user_id])
            ->where(['su.mobile'=>$user->mobile])
            ->field('su.nickname,su.avatar,s.audit_status,s.shop_id,sa.is_applicant,s.address,s.subject_type,s.category_id,s.shop_name,s.banner_img')
            ->select();

        $subjectType = $this->getSubjectType();

        foreach ($lists as $k=>$v){

            $lists[$k]['subject_type_name']=$v['subject_type']?$subjectType[$v['subject_type']]:'';
            $category = Category::get($v['category_id']);
            $lists[$k]['category_name']=$category?$category->getAttr('name'):'';


           /* if ($v['audit_status']==0){
                $lists[$k]['banner_img'] = explode(',',$v['banner_img'])[0];
            }*/
        }
        return $lists;
    }

    public function shopInfo($user_id)
    {
        $shop_user = ShopUser::get($user_id);

        $shop = \app\shopapi\model\Shop::where(['shop_id'=>$shop_user->shop_id])->find();

        $category_name = '';
        if ($shop->category_id){
            $category = \app\admin\model\shop\Category::get($shop->category_id);
            $category_name = $category_name.$category->getAttr('name');
            if ($category->pid){
                $p_category = \app\admin\model\shop\Category::get($category->pid);
                $category_name = $p_category->getAttr('name').'/'.$category_name;
            }
        }

        $subjectType = $this->getSubjectType();

        $data = [
            'reg_mobile'=>$shop_user->mobile,
            'nickname'=>$shop_user->mobile,
            'commission_rate'=>$shop->commission_rate,
            'shop_name'=>$shop->shop_name,
            'category_id'=>$shop->category_id,
            'category_name'=>$category_name,
            'address'=>$shop->address,
            'mobile'=>$shop->mobile,
            'subject_type'=>$subjectType[$shop->subject_type],
            'id_card_num'=>$shop->id_card_num,
            'id_card_name'=>$shop->id_card_name,
            'banner_img'=>$shop->banner_img,
            'start_time'=>$shop->start_time,
            'end_time'=>$shop->end_time,
            'lng'=>$shop->lng,
            'lat'=>$shop->lat,
            'work_week'=>$shop->work_week?$this->getWorkWeek($shop->work_week):'未知'
        ];

        return $data;
    }


    public function hasDuplicates($array1, $array2) {
        $diff = array_diff(array_merge($array1, $array2), array_intersect($array1, $array2));
        return !empty($diff);
    }

    public function getWeek()
    {
        return [1=>'周一',2=>'周二',3=>'周三',4=>'周四',5=>'周五',6=>'周六',0=>'周日'];
    }

    //转换店铺的营业日期
    public function getWorkWeek($week)
    {
        $week = explode(',',$week);
        $week_list = [0,1,2,3,4,5,6];

        $res = $this->hasDuplicates($week,$week_list);
        $week_list = $this->getWeek();

        if ($res){
            $work_week = [];
            foreach ($week as $k=>$v){
                array_push($work_week,$week_list[$v]);
            }
            return $work_week;
        } else {
            return '周一至周日';
        }
    }

    //修改店铺基础信息
    public function editShopBasisInfo($param)
    {

        $shop_name = $param['shop_name'] ?? '';
        $category_id = $param['category_id'] ?? 0;
        $address = $param['address'] ?? '';
        $lat = $param['lat'] ?? '';
        $lng = $param['lng'] ?? '';
        $start_time = $param['start_time'] ?? '';
        $end_time = $param['end_time'] ?? '';
        $work_week = $param['work_week'] ?? '';
        $banner_img = $param['banner_img'] ?? '';
        $interior_img = $param['interior_img'] ?? '';
        //$group_photo_img = $param['group_photo_img'] ?? '';
        $realname = $param['realname'] ?? '';
        $mobile = $param['mobile'] ?? '';
        //$email = $param['email'] ?? '';

        Db::startTrans();

        try {
            $shop = \app\shopapi\model\Shop::get($param['shop_id']);

            $data = [
                'shop_name'=>$shop_name,
                'category_id'=>$category_id,
                'address'=>$address,
                'lat'=>$lat,
                'lng'=>$lng,
                'start_time'=>$start_time,
                'end_time'=>$end_time,
                'work_week'=>$work_week,
                'banner_img'=>$banner_img,
                'interior_img'=>$interior_img,
                //'group_photo_img'=>$group_photo_img,
                'realname'=>$realname,
                'mobile'=>$mobile,
                //'email'=>$email,
            ];

            $res =  $shop->save($data);

            if ($res){
                Db::commit();
                return $res;
            } else {
                Db::rollback();
                throw new \Exception('修改失败');
            }

        } catch (\Exception $e) {
            Db::rollback();
            throw new \Exception($e->getMessage());
        }
    }

    //修改店铺资质信息
    public function editShopAptitudeInfo($param)
    {

        $front_id_card_img = $param['front_id_card_img'] ?? '';
        $reverse_id_card_img = $param['reverse_id_card_img'] ?? '';
        $id_card_name = $param['id_card_name'] ?? '';
        $id_card_num = $param['id_card_num'] ?? '';
        $id_card_start_time = $param['id_card_start_time'] ?? '';
        $id_card_end_time = $param['id_card_end_time'] ?? '';
        $legal_person_phone = $param['legal_person_phone'] ?? '';
        $signature_img = $param['signature_img'] ?? '';

        Db::startTrans();

        try {
            $shop = \app\shopapi\model\Shop::get($param['shop_id']);

            $data = [
                'front_id_card_img'=>$front_id_card_img,
                'reverse_id_card_img'=>$reverse_id_card_img,
                'id_card_name'=>$id_card_name,
                'id_card_num'=>$id_card_num,
                'id_card_start_time'=>$id_card_start_time,
                'id_card_end_time'=>$id_card_end_time,
                'legal_person_phone'=>$legal_person_phone,
                'signature_img'=>$signature_img,
            ];

            $res =  $shop->save($data);

            if ($res){
                Db::commit();
                return $res;
            } else {
                Db::rollback();
                throw new \Exception('修改失败');
            }

        } catch (\Exception $e) {
            Db::rollback();
            throw new \Exception($e->getMessage());
        }
    }

    //生成收款码
    public function collectionCode($shop_id)
    {
        $page = 'otherpages/payorder/payorder';
        $qrcode_param = [
            'id'=>$shop_id
        ];
        $qrcode_info = $this->getQrcode('h5', $page, $qrcode_param);

        if ($qrcode_info[ 'code' ] < 0) throw new \Exception($qrcode_info['msg']);

        return $qrcode_info[ 'data' ][ 'path' ];

    }

    /**
     * 获取二维码
     * @param unknown $app_type 请求类型
     * @param unknown $page uniapp页面路径
     * @param unknown $qrcode_param 二维码携带参数
     * @param string $promotion_type 活动类型 null为无活动
     */
    private function getQrcode($app_type, $page, $qrcode_param)
    {
        $data = [
            'app_type' => $app_type,
            'type' => 'get',
            'data' => $qrcode_param,
            'page' => $page,
            'qrcode_path' => 'upload/qrcode/shop_pay',
            'qrcode_name' => 'shop_pay' . '_' . $qrcode_param[ 'id' ],
        ];
        $qrcode_model = new Qrcode();

        if ($app_type=='weapp'){
            $res = $qrcode_model->createWxQrcode($data);
        } else {
            $res = $qrcode_model->createQrcode($data);
        }

        return $res;
    }



    //商户进件回调
    public function notify($data,$event_type)
    {

        $event = _json_decode($data,true);

        Log::error('入驻回调:'.json_encode($event,320));
        if ($event_type=='member.merchant.open'){
            //商户开通结果通知
            $member_no = $event['member_no'];
            $out_member_no = $event['out_member_no'];
            $merchant_no = $event['merchant_no'];
            $out_merchant_no = $event['out_merchant_no'];
            $channel_merchant_no = $event['channel_merchant_no'];//渠道商户号
            $merchant_status = $event['merchant_status'];//有效3
            $channel_terminal_no = $event['channel_terminal_no'];

            $shop_info = Shop::get(['out_member_no'=>$out_member_no,'out_merchant_no'=>$out_merchant_no]);



            if ($merchant_status==3){
                $shop_info->merchant_no = $merchant_no;
                $shop_info->member_no = $member_no;
                $shop_info->channel_merchant_no = $channel_merchant_no;
                $shop_info->channel_terminal_no = $channel_terminal_no;
                /*if (!$shop_info->checkstand_merchant_no){
                    $model = new \app\shopapi\model\lakala\ShopInfeed();
                    $model->addTerminal($member_no,$channel_merchant_no);
                }*/
                /*$merchant_data=[
                    'shop_id'=>$shop_info->shop_id,
                    'merchant_no'=>$merchant_no,
                    'channel_merchant_no'=>$channel_merchant_no,
                    'channel_terminal_no'=>$channel_terminal_no,
                ];
                $model = new ShopMerchantNo();
                $detail = ShopMerchantNo::get(['merchant_no'=>$merchant_no]);
                if (!$detail)$model->save($merchant_data);*/
            }
            $shop_info->audit_status = $merchant_status;
            $res = $shop_info->save();
        } elseif ($event_type=='member.open'){
            //会员开户结果通知

            $member_no = $event['member_no'];
            $out_member_no = $event['out_member_no'];
            $mobile = $event['mobile'];
            //$member_type = $event['member_type'];
            //$member_state = $event['member_state'];
            /*$shop_user = ShopUser::get(['mobile'=>$mobile]);
            if ($shop_user){
                $shop_user->member_type = $member_type;
                $shop_user->member_state = $member_state;
                $shop_user->save();
            }*/
            //ShopUser::update(['member_type'=>$member_type,'member_state'=>$member_state],['mobile'=>$mobile]);

            //$shop_info = Shop::get(['out_member_no'=>$out_member_no]);

            //$shop_info->member_no = $member_no;
            //$res = $shop_info->save();
        } elseif ($event_type=='esign.create'){
            //电子签约通知

            $esign_project_code = $event['esign_project_code'];
            $contract_no = $event['contract_no'];
            $esign_status = $event['esign_status'];
            $pb_member_sign_status = $event['pb_member_sign_status'];
            $member_list = $event['member_list'];

            foreach ($member_list as $k=>$v){
                $shop_info = Shop::get(['member_no'=>$v['member_no']]);

                $shop_info->esign_project_code = $esign_project_code;
                $shop_info->contract_no = $contract_no;
                $shop_info->esign_status = $esign_status;
                $shop_info->pb_member_sign_status = $pb_member_sign_status;

                $shop_info->save();
            }

        }

        return true;
    }


    //商户绑卡回调
    public function bindCardNotify($data,$event_type)
    {
        $event = _json_decode($data,true);

        Log::error('绑卡回调:'.json_encode($event,320));

        $member_no = $event['member_no'];
        $operate_type = $event['operate_type'];//1：绑卡2：解绑3：设置结算卡
        $card_no = $event['card_no'];//银行卡编号
        $bank_card_no = $event['bank_card_no'];//银行卡号
        $is_settle_card = $event['is_settle_card'];//是否结算卡,true是
        $bank_contact_name = $event['bank_contact_name'];//支行
        $bank_contact_no = $event['bank_contact_no'];//支行号

        $bank_info = Bank::get(['number'=>$bank_contact_no]);
        $shop = Shop::get(['member_no'=>$member_no]);
        if ($event_type=='member.bank.card'){

            if ($operate_type==3){
                $shop->bank_name = $bank_info['bank_name'];
                $shop->bank_num = $bank_card_no;
                $shop->bank = $bank_contact_name;
                $shop->bank_code = $bank_contact_no;
                $shop->bank_card_id = $card_no;
                $shop->save();
            }

        }

        return true;
    }

    //收银台回调
    public function terminalNotify($data,$event_type)
    {
        $event = _json_decode($data,true);

        Log::error('收银台商户号回调:'.json_encode($event,320));
        if ($event_type=='member.merchant.term'){
            $member_no = $event['member_no'];

            $list = $event['terms'];

            $shop = Shop::get(['member_no'=>$member_no]);

            $model = new ShopMerchantNo();

            foreach ($list as $k=>$v){
                $merchant_data=[
                    'shop_id'=>$shop->shop_id,
                    'merchant_no'=>$v['merchant_no'],
                    'channel_merchant_no'=>$v['channel_merchant_no'],
                    'channel_terminal_no'=>$v['channel_terminal_no'],
                    'buis_type_code'=>$v['buis_type_code'],
                    'buis_type_name'=>$v['buis_type_name'],
                    'busi_active_no'=>$v['busi_active_no'],
                ];
                if ($v['buis_type_code']=='QR_CODE_CARD'){
                    $checkstand_merchant_no = $v['merchant_no'];
                }
                $detail = ShopMerchantNo::get(['merchant_no'=>$v['merchant_no']]);
                if (!$detail)$model->save($merchant_data);

            }

            if (empty($shop->checkstand_merchant_no)||$shop->checkstand_merchant_no==1){
                $shop->checkstand_merchant_no = $checkstand_merchant_no;
            }

            $shop->save();

            return $event;
        }



    }

}
